package com.spider.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.spider.constant.KubazhaUrl;
import com.spider.entity.KubazhaEntity;
import com.spider.entity.KubazhaFailEntity;
import com.spider.mapper.HeownsJiliMapper;
import com.spider.mapper.HeownsKubazhaMapper;
import com.spider.util.HttpTokenUtil;
import com.spider.util.KubazhaUtil;
import com.spider.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 库巴扎
 */
@Service
public class KubazhaServiceImpl implements KubazhaService {

    @Autowired
    RestTemplate restTemplate;
    @Autowired
    HeownsJiliMapper mapper;
    @Autowired
    HeownsKubazhaMapper kubazhaMapper;
    @Autowired
    private JiliUtilService utilService;

    private final Logger logger = LoggerFactory.getLogger(KubazhaServiceImpl.class);

    /**
     * 获取token+ucode
     */
    public static Map<String, String> getToken() {
        Map<String, String> map = new HashMap<>();

        // Set up the request URL
        String url = KubazhaUrl.PRODUCT_URL + KubazhaUrl.TOKEN_URL;

        // Set up the parameters
        MultiValueMap<String, String> paramMap = new LinkedMultiValueMap<>();
        paramMap.add("loginname", KubazhaUrl.LOGINNAME_PROD);
        paramMap.add("ukey", KubazhaUrl.UKEY_PORD);
        paramMap.add("vcode", KubazhaUrl.VCODE_RROD);

        // Set up headers
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        // Create the request entity
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(paramMap, headers);

        // Make the POST request
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> result = restTemplate.postForEntity(url, requestEntity, String.class);

        System.out.println("返回结果：" + result);
        if (result.getStatusCode().is2xxSuccessful()) {
            String res = StringUtil.unicodeDecode(result.getBody());
            JSONObject jb = JSONObject.parseObject(res);
            Integer flag = jb.getInteger("flag");
            if (flag != null && flag == 1) {
                JSONArray rdate = jb.getJSONArray("rdate");
                if (rdate != null && !rdate.isEmpty()) {
                    JSONObject rdate0 = rdate.getJSONObject(0);
                    String token = rdate0.getString("token");
                    String ucode = rdate0.getString("ucode");
                    String timestamp = rdate0.getString("timestamp");
                    map.put("token", token);
                    map.put("ucode", ucode);
                    map.put("timestamp", timestamp);
                    System.out.println(token);
                    System.out.println(ucode);
                    System.out.println(timestamp);
                }
            }
        }
        return map;
    }


    /**
     * 获取token+ucode
     */
    private static Map<String, String> getTestToken() {
        Map<String, String> map = new HashMap<>();

        // Set up the request URL
        String url = KubazhaUrl.TEST_URL + KubazhaUrl.TOKEN_URL;

        // Set up the parameters
        MultiValueMap<String, String> paramMap = new LinkedMultiValueMap<>();
        paramMap.add("loginname", KubazhaUrl.LOGINNAME);
        paramMap.add("ukey", KubazhaUrl.UKEY);
        paramMap.add("vcode", KubazhaUrl.VCODE);

        // Set up headers
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        // Create the request entity
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(paramMap, headers);

        // Make the POST request
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> result = restTemplate.postForEntity(url, requestEntity, String.class);

        System.out.println("返回结果：" + result);
        if (result.getStatusCode().is2xxSuccessful()) {
            String res = StringUtil.unicodeDecode(result.getBody());
            JSONObject jb = JSONObject.parseObject(res);
            Integer flag = jb.getInteger("flag");
            if (flag != null && flag == 1) {
                JSONArray rdate = jb.getJSONArray("rdate");
                if (rdate != null && !rdate.isEmpty()) {
                    JSONObject rdate0 = rdate.getJSONObject(0);
                    String token = rdate0.getString("token");
                    String ucode = rdate0.getString("ucode");
                    String timestamp = rdate0.getString("timestamp");
                    map.put("token", token);
                    map.put("ucode", ucode);
                    map.put("timestamp", timestamp);
                    System.out.println(token);
                    System.out.println(ucode);
                    System.out.println(timestamp);
                }
            }
        }
        return map;
    }


/*    *//**
     * 价格修改
     * @param  num 默认为空，如果不为空则只跑一次
     *//*
    @Override
    public void priceUpdate(String num){
        //拼接参数
        String url= JiLiUrl.PRODUCT_URL+JiLiUrl.ASYNC_TASK_NEW;
        String token = this.getToken();
        System.out.println(token);
        //查询结果集
        List<JiliEntity> list = mapper.selectByDate();
        if(list.isEmpty()){
            logger.info("库巴扎价格推送无数据，推送结束");
        }else{
            logger.info("库巴扎价格推送查询结果集数量为"+list.size());
                try{
                    JSONObject body= JiLiUtil.getUpdatePriceBodyNew(list);
                    if(body==null){
                        logger.info("实体拼接数据失败缺乏数据，跳过此数据:");
                    }
                    String res=HttpTokenUtil.postRequest(token,url,body);
                    System.out.println(res);
                    JiliRecord record=new JiliRecord();
                    record.setResult(res);
                    JSONObject jb=JSONObject.parseObject(res);
                    JSONObject content= (JSONObject) jb.get("content");
                    String taskId= (String) content.get("task_id");
                    record.setTaskId(taskId);
                    record.setType("修改价格");
                    record.setStatus("初始化");
                    String hs="";
                    for(JiliEntity entity:list){
                        hs=entity.getHuohao()+",";
                        mapper.updateJiliPrice(entity);
                    }
                    record.setParams(hs);
                    mapper.saveRecord(record);
                }catch (Exception e){
                    e.printStackTrace();
                    logger.error("库巴扎价格推送失败，失败原因："+e.getMessage());
                }
            }

    }*/
    /**
     * 库存新增
     * @param num 不为空则只推送一条
     */
    @Override
    public void stockInsert(String num){
        //拼接参数
        String url= KubazhaUrl.PRODUCT_URL+KubazhaUrl.INSERT_URL;
        System.out.println("调用url为："+url);
        Map tokenMap = this.getToken();
        //拼接body
        List<KubazhaEntity> list = kubazhaMapper.selectKubazhaInsert();
        if(list.isEmpty()){
            logger.info("库巴扎新产品库存推送无数据，推送结束");
        }else{
            logger.info("库巴扎新产品库存推送查询结果集数量为"+list.size());
            try{
                MultiValueMap<String, String> body= KubazhaUtil.insertProduceBody(list,tokenMap);
                logger.info("库巴扎新产品库存推送json为"+body.toString());
                String res= HttpTokenUtil.postRequestFormUNLENCODED(url,body);
                System.out.println(res);
                JSONObject jb=JSONObject.parseObject(res);
                Integer flag= (Integer) jb.get("flag");
                if(flag!=null&&flag==1){
                    logger.info("开始插入本地新增数据库：");
                    for(KubazhaEntity entity:list){
                        kubazhaMapper.saveInsert(entity);
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
                logger.error("库巴扎新产品库存推送失败，失败原因："+e.getMessage());
            }
        }
    }

    /**
     * 修改价格
     * @param num 不为空则只推送一条
     */
    @Override
    public void updatePrice(String num){
        //拼接参数
        String url= KubazhaUrl.PRODUCT_URL+KubazhaUrl.INSERT_URL;
        System.out.println("调用url为："+url);
        Map tokenMap = this.getToken();
        //拼接body
        List<KubazhaEntity> list = kubazhaMapper.selectByDate();
        if(list.isEmpty()){
            logger.info("库巴扎修改价格推送无数据，推送结束");
        }else{
            logger.info("库巴扎修改价格推送查询结果集数量为"+list.size());
            try{
                MultiValueMap<String, String> body= KubazhaUtil.insertProduceBody(list,tokenMap);
                if(body==null){
                    logger.info("实体拼接数据失败缺乏数据，跳过此数据");
                }
                logger.info("库巴扎修改价格推送json为"+body.toString());
                String res=HttpTokenUtil.postRequestFormUNLENCODED(url,body);
                System.out.println(res);
                JSONObject jb=JSONObject.parseObject(res);
                Integer flag= (Integer) jb.get("flag");
                if(flag!=null&&flag==1){
                    logger.info("开始修改本地数据库：");
                    for(KubazhaEntity entity:list){
                        kubazhaMapper.updateKubazhaPrice(entity);
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
                logger.error("库巴扎修改价格推送失败，失败原因："+e.getMessage());
            }
        }
    }

    /**
     * 修改库存
     * @param num 不为空则只推送一条
     */
    @Override
    public void updateStock(String num){
        //拼接参数
        String url= KubazhaUrl.PRODUCT_URL+KubazhaUrl.INSERT_URL;
        System.out.println("调用url为："+url);
        Map tokenMap = this.getToken();
        //拼接body
        List<KubazhaEntity> list = kubazhaMapper.selectKubazhaStock();
        if(list.isEmpty()){
            logger.info("库巴扎修改库存推送无数据，推送结束");
        }else{
            logger.info("库巴扎修改库存推送查询结果集数量为"+list.size());
            try{
                MultiValueMap<String, String> body= KubazhaUtil.insertProduceBody(list,tokenMap);
                if(body==null){
                    logger.info("实体拼接数据失败缺乏数据，跳过此数据");
                }
                logger.info("库巴扎修改库存推送json为"+body.toString());
                String res=HttpTokenUtil.postRequestFormUNLENCODED(url,body);
                System.out.println(res);
                JSONObject jb=JSONObject.parseObject(res);
                Integer flag= (Integer) jb.get("flag");
                if(flag!=null&&flag==1){
                    logger.info("开始修改本地数据库：");
                    for(KubazhaEntity entity:list){
                        kubazhaMapper.updateKubazhaStock(entity);
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
                logger.error("库巴扎修改库存推送失败，失败原因："+e.getMessage());
            }
        }
    }

    @Override
    public void deleteProduct(String num){
        //拼接参数
        String url= KubazhaUrl.PRODUCT_URL+KubazhaUrl.DELETE_URL;
        Map tokenMap = this.getToken();
        //拼接body
        List<KubazhaEntity> list = kubazhaMapper.selectKubazhaDelete();
        if(list.isEmpty()){
            logger.info("库巴扎下架产品推送无数据，推送结束");
        }else{
            logger.info("库巴扎下架产品推送查询结果集数量为"+list.size());
            try{
                MultiValueMap<String, String> body= KubazhaUtil.deleteProductBody(list,tokenMap);
                if(body==null){
                    logger.info("实体拼接数据失败缺乏数据，跳过此数据");
                }
                System.out.println(body.toString());
                String res=HttpTokenUtil.postRequestFormUNLENCODED(url,body);
                JSONObject jb=JSONObject.parseObject(res);
                Integer flag= (Integer) jb.get("flag");
                if(flag!=null&&flag==1){
                    logger.info("库巴扎下架返回："+jb.toString());
                    for(KubazhaEntity entity:list){
                        kubazhaMapper.deleteKubazhaProduct(entity);
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
                logger.error("库巴扎下架产品推送失败，失败原因："+e.getMessage());
            }
        }

    }

    @Override
    public void getResult(String date){
        //拼接参数
        String url= KubazhaUrl.PRODUCT_URL+KubazhaUrl.RESULT_URL;
        Map tokenMap = this.getToken();
        //拼接body
        try{
            MultiValueMap<String, Object> body= KubazhaUtil.getResultBody(tokenMap,date);
            String res=HttpTokenUtil.postRequestFormUNLENCODEDOjbect(url,body);
            JSONObject jb=JSONObject.parseObject(res);
            System.out.println(body.toString());
            Integer flag= (Integer) jb.get("flag");
            if(flag!=null&&flag==1){
                String message= (String) jb.get("message");
                JSONArray jsonArray= (JSONArray) jb.get("data");
                if(CollectionUtils.isEmpty(jsonArray)){
                    System.out.println("无错误数据");
                }else{
                    for(Object object:jsonArray){
                        JSONObject jbRes= (JSONObject) object;
                        String  hs = (String) jbRes.get("货号");
                        String  brand = (String) jbRes.get("品牌");
                        String  nameCn = (String) jbRes.get("中文名称");
                        String  bzdw = (String) jbRes.get("包装单位");
                        String  cas = (String) jbRes.get("cas");
                        String  reason = (String) jbRes.get("失败原因");
                    }

                }
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("库巴扎下架产品推送失败，失败原因："+e.getMessage());
        }


    }


    /**
     * 查询失败结果
     * @param date
     */
    @Override
    public void getFailLogs(String date){
        Map tokenMap = this.getToken();
        boolean flag =true;
        int page =1;
        String url= KubazhaUrl.PRODUCT_URL+KubazhaUrl.RESULT_URL;
        List<KubazhaFailEntity> list = new ArrayList<KubazhaFailEntity>();
        try{
            while (flag){
                String failResult = KubazhaUtil.getFailResult(tokenMap,date,page,url);
                JSONObject jb=JSONObject.parseObject(failResult);
                Integer resFlag= (Integer) jb.get("flag");
                if(resFlag!=null&&resFlag==1){
                    String message= (String) jb.get("message");
                    JSONArray jsonArray= (JSONArray) jb.get("data");
                    if(CollectionUtils.isEmpty(jsonArray)){
                        System.out.println("无错误数据");
                    }else{
                        System.out.println(jsonArray.size());
                        //判断如果长度等于100则可能还有下一批数据
                        if(jsonArray.size()==100){
                            page++;
                            flag = true;
                        }else{
                            flag = false;
                        }
                        for(Object object:jsonArray){
                            KubazhaFailEntity entity =new KubazhaFailEntity();
                            JSONObject jbRes= (JSONObject) object;
                            String  huohao = (String) jbRes.get("货号");
                            entity.setHuohao(huohao);
                            String  brand = (String) jbRes.get("品牌");
                            entity.setBrand(brand);
                            String  gg = (String) jbRes.get("包装规格");
                            entity.setGg(gg);
                            String  nameCn = (String) jbRes.get("中文名称");
                            entity.setName(nameCn);
                            String  priceOld = (String) jbRes.get("目录价");
                            if(StringUtil.isNotEmpty(priceOld)){
                                BigDecimal priceOldB = new BigDecimal(priceOld);
                                entity.setPrice(priceOldB);
                            }
                            String  jhq = (String) jbRes.get("交货期");
                            entity.setJiaohuori(jhq);
                            String  productNo = (String) jbRes.get("产品分类");
                            String  kc = (String) jbRes.get("库存");
                            entity.setKc(kc);
                            String  uploadDate = (String) jbRes.get("上传日期");
                            entity.setUploadDate(uploadDate);
                            String  rl = (String) jbRes.get("容量");
                            String  rlUnit = (String) jbRes.get("容量单位");
                            String  bzdw = (String) jbRes.get("包装单位");
                            entity.setUnit(bzdw);
                            String  cas = (String) jbRes.get("cas");
                            entity.setCas(cas);
                            String  reason = (String) jbRes.get("失败原因");
                            entity.setFailReason(reason);
                            list.add(entity);
                        }
                    }
                }
            }
            for(KubazhaFailEntity dto:list){
                kubazhaMapper.saveInsertFailLog(dto);
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("库巴扎查询失败记录失败，失败原因："+e.getMessage());
        }

    }

    /**
     * 读取错误日志并处理
     */
    public void resendFailLog(){

    }


}
